package com.kai.steering.data.service.ctl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.kai.steering.data.service.entity.domainObject.KnowledgeDO;
import com.kai.steering.data.service.entity.domainObject.TestDO;
import com.kai.steering.data.service.entity.domainObject.WarehouseDO;
import com.kai.steering.data.service.entity.dto.TestDTO;
import com.kai.steering.data.service.entity.dto.WarehouseDTO;
import com.kai.steering.data.service.entity.dto.WarehouseQueryDTO;
import com.kai.steering.data.service.entity.po.Warehouse;
import com.kai.steering.data.service.entity.vo.KnowledgeVO;
import com.kai.steering.data.service.entity.vo.TestVO;
import com.kai.steering.data.service.entity.vo.WarehouseVO;
import com.kai.steering.data.service.service.TestService;
import com.kai.steering.data.service.service.WarehouseService;
import com.kai.steering.common.vo.Result;
import com.kai.steering.common.web.ctl.BaseController;
import com.kai.steering.data.service.util.EqualsUtil;
import com.kai.steering.exception.CanUsedException;
import com.kai.steering.exception.ExcelException;
import com.kai.steering.exception.UimpException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import java.io.IOException;
import java.io.Serializable;
import javax.annotation.Resource;
import javax.validation.Valid;

import com.kai.steering.common.vo.Page;
import com.kai.steering.common.web.vo.ReturnCodeExt;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <pre>
 * 仓库 前端控制器
 * </pre>
 *
 * @author kai
 * @since 2022-02-23
 */
@Slf4j
@RestController
@RequestMapping("/warehouse")
@Api(tags = "仓库 API")
public class WarehouseController extends BaseController {
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private TestService testService;

    @PostMapping
    @ApiOperation(value = "仓库-添加")
    public Result<WarehouseVO> addWarehouse(@Valid @RequestBody WarehouseDTO warehouseDTO) {

        /**
         * 参数检查
         */
        //id
        warehouseDTO.setWarehouseId(null);
        //name
        if (StringUtils.isEmpty(warehouseDTO.getWarehouseName())) {
            return Result.failed("参数不完整");
        }

        /**
         * 构建新对象
         */
        WarehouseDO warehouseDO = new WarehouseDO(warehouseDTO);

        /**
         * 调用服务
         */
        //保存
        WarehouseDO warehouseSave = warehouseService.saveWarehouse(warehouseDO);

        WarehouseVO warehouseVO = new WarehouseVO(warehouseSave);
        return Result.ok(warehouseVO);
    }


    @PutMapping("/{id}")
    @ApiOperation(value = "仓库-编辑")
    public Result<WarehouseVO> updateWarehouse(@PathVariable("id") Serializable id, @Valid @RequestBody WarehouseDTO warehouseDTO) {
        /**
         * 参数验证
         */
        //id
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("参数不完整");
        }
        warehouseDTO.setWarehouseId(id.toString());
        //name
//        if (StringUtils.isEmpty(warehouseDTO.getWarehouseName()))
//            throw ReturnCodeExt.PARAMETER_CHECK.getException("name为空");
        WarehouseDO warehouseDO = new WarehouseDO(warehouseDTO);
        /**
         * 调用服务
         */
        //修改属性
        WarehouseDO warehouseDOUpdara= warehouseService.updateWarehouse(id, warehouseDO);
        if (warehouseDOUpdara!=null){
            return Result.ok( new WarehouseVO(warehouseDOUpdara));
        }
        return Result.failed();
    }


    @DeleteMapping("/{id}")
    @ApiOperation(value = "仓库-删除")
    public Result<Boolean> deleteWarehouse(@PathVariable("id") Serializable id) {
        /**
         * 参数验证
         */
        //id
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("参数不完整");
        }

        boolean flag = warehouseService.deleteWarehouse(id);
        if (flag){
            return Result.ok();
        }
        return Result.failed();
    }


    @PostMapping("/get/{id}")
    @ApiOperation(value = "仓库-详情")
    public Result<WarehouseVO> getWarehouse(@PathVariable("id") Serializable id,@RequestBody  Map parameterList) {
        /**
         * 参数验证
         */
        //id
        if (StringUtils.isEmpty(id.toString())) {
            return Result.failed("参数不完整");
        }
        HashMap<String, Boolean> parameterMap = new HashMap<>();
        boolean knowledgeExist=false;
        if (EqualsUtil.objectEquals(parameterList.get("knowledgeExist"),"1",1)) {

            knowledgeExist=true;
        }
        parameterMap.put("knowledgeExist",knowledgeExist);
        boolean subordinateExist=false;

        if (EqualsUtil.objectEquals(parameterList.get("subordinateExist"),"1",1)) {
            subordinateExist=true;
        }
        parameterMap.put("subordinateExist",subordinateExist);

        boolean testExist=false;

        if (EqualsUtil.objectEquals(parameterList.get("testExist"),"1",1)) {
            testExist=true;
        }
        parameterMap.put("testExist",testExist);
            /**
             * 调用服务
             */
        WarehouseDO warehouseById = warehouseService.getWarehouseById(id,parameterMap);

        WarehouseVO warehouseQueryVo = new WarehouseVO(warehouseById);
        if (warehouseQueryVo == null||StringUtils.isEmpty(warehouseQueryVo.getWarehouseId())){
            throw ReturnCodeExt.PARAMETER_CHECK.getException("id[" + id + "]对象不存在");
        }

        return Result.ok(warehouseQueryVo);
    }

    @PostMapping("/test/{id}")
    @ApiOperation(value = "仓库-试卷")
    public Result<List<TestVO>> getWarehouseTest(@PathVariable("id") Serializable id, @RequestBody  Map parameterList) {
        /**
         * 参数验证
         */

        /**
         * 调用服务
         */
        List<TestDO> testDOS = warehouseService.getWarehouseTestById(id);
        List<TestVO> testVOS = TestVO.convertTestVO(testDOS);


        return Result.ok(testVOS);
    }

    @PostMapping("/list")
    @ApiOperation(value = "仓库-综合查询")
    public Result<Page<WarehouseVO>> getWarehousePageList(@Valid @RequestBody WarehouseQueryDTO warehouseQueryDTO) {
        /**
         * 参数验证
         */
        /**
         * 参数验证
         */
        //创建时间  都为空 或（都不为空且开始<=结束）
        if ((warehouseQueryDTO.getCreationDateOrigin() == null || warehouseQueryDTO.getCreationDateTerminus() == null) ||
                (warehouseQueryDTO.getCreationDateOrigin().getTime() > warehouseQueryDTO.getCreationDateTerminus().getTime())) {
            return Result.failed("创建时间查询参数错误");
        }
        Page<WarehouseVO> paging = warehouseService.getWarehousePageList(warehouseQueryDTO);
        return Result.ok(paging);
    }


    @GetMapping("/list")
    @ApiOperation(value = "仓库-全部列表")
    public Result<List<WarehouseVO>> getWarehouseAllList() {
        List<WarehouseDO> allWarehouse = warehouseService.getAllWarehouse();

        List<WarehouseVO> list = allWarehouse.stream()
                .map(warehouse -> {
                    WarehouseVO warehouseVO = new WarehouseVO();
                    BeanUtil.copyProperties(warehouse, warehouseVO);
                    return warehouseVO;
                })
                .collect(Collectors.toList());
        return Result.ok(list);
    }
    @PostMapping("/addTest/{id}")
    @ApiOperation(value = "仓库-添加试卷")
    public Result addTest(@PathVariable("id") Serializable id,@Valid @RequestBody TestDTO testDTO){
        //参数检查
        if (StringUtils.isEmpty(testDTO.getTestName())) {
            throw ReturnCodeExt.PARAMETER_CHECK.getException("属性不全");
        }
        //构建新对象
        TestDO testDO = new TestDO(testDTO);
        testDO.setTestId(null);
        testDO.setQuestions(null);
        try {
            warehouseService.addTest(id.toString(),testDO);
        }catch (CanUsedException canUsedException){
            return Result.failed("添加失败");
        }
        return Result.ok("添加成功");
    }

    @PostMapping("/importTest/{id}")
    @ApiOperation(value = "仓库-导入试卷")
    public ResponseEntity<Resource> importTest(@PathVariable("id") Serializable id,@RequestParam("importTestFile") MultipartFile file){
        // 检查上传文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
        }

        // 检查文件类型，根据你的需求，你可以检查扩展名或者 MIME 类型
        String contentType = file.getContentType();
        String filename = file.getOriginalFilename();

        // 这里只是一个简单的示例，判断文件名后缀是否为Excel格式，一般为 .xls 或 .xlsx
        if (filename == null || !(filename.endsWith(".xls") || filename.endsWith(".xlsx"))) {
            return ResponseEntity.status(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
                    .body(null); // 415 状态码表示不支持的媒体类型
        }


        try {
            warehouseService.importTest(id.toString(),file);
        }catch (CanUsedException canUsedException){
            List<ExcelException> excelExceptions = (List<ExcelException>)canUsedException.getData();
            if (excelExceptions.size() > 0) {
                try {
                    ResponseEntity responseEntity = UimpException.generateResponse(file, excelExceptions);
                    return responseEntity;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ResponseEntity successResource = ResponseEntity.ok("导入成功");
        return successResource;
    }
    @GetMapping("/moveTestInWarehouse/{warehouseTarget}/{warehouseId}/{testId}")
    @ApiOperation(value = "仓库-移动试卷")
    public Result<Boolean> moveTestInWarehouse(@PathVariable("warehouseTarget") Serializable warehouseTarget,
                                               @PathVariable("warehouseId") Serializable warehouseId,@PathVariable("testId") Serializable testId){
        /**
         * 参数验证
         */
        //testId
        if (StringUtils.isEmpty(testId.toString())) {
            return Result.failed("testId为空");
        }
        //testId
        if (StringUtils.isEmpty(warehouseTarget.toString())) {
            return Result.failed("warehouseTarget 为空");
        }
        //warehouseId
        if (StringUtils.isEmpty(warehouseId.toString())) {
            return Result.failed("warehouseId为空");
        }
        boolean b= warehouseService.moveTestInWarehouse(warehouseTarget,warehouseId,testId);
        return Result.judge(b);

    }
    @GetMapping("/moveWarehouse/{warehouseTarget}/{warehouseId}")
    @ApiOperation(value = "仓库-移动仓库")
    public Result<Boolean> moveWarehouse(@PathVariable("warehouseTarget") Serializable warehouseTarget,@PathVariable("warehouseId") Serializable warehouseId){
        /**
         * 参数验证
         */
        //warehouseFirst
        if (StringUtils.isEmpty(warehouseTarget.toString())) {
            return Result.failed("warehouseTarget为空");
        }
        //warehouseId
        if (StringUtils.isEmpty(warehouseId.toString())) {
            return Result.failed("warehouseId为空");
        }
        if (warehouseId.toString().equals(warehouseTarget.toString())){
            return Result.failed("仓库相同");
        }

        boolean b=warehouseService.moveWarehouse(warehouseTarget,warehouseId);
        return Result.judge(b);

    }

    @PostMapping("/treeWarehouse/{warehouseId}")
    @PreAuthorize("hasAnyRole('JUESE_1')")
    @ApiOperation(value = "仓库-查询仓库树")
    public Result<WarehouseVO> treeWarehouse(@PathVariable("warehouseId") Serializable warehouseId,@RequestBody  Map parameterList){
        /**
         * 参数验证
         */
        if (StringUtils.isEmpty(warehouseId.toString())) {
            return Result.failed("warehouseId为空");
        }

        HashMap<String, Boolean> parameterMap = new HashMap<>();
        boolean knowledgeExist=false;
        if (EqualsUtil.objectEquals(parameterList.get("knowledgeExist"),"1",1)) {

            knowledgeExist=true;
        }
        parameterMap.put("knowledgeExist",knowledgeExist);
        boolean testExist=false;
        if (EqualsUtil.objectEquals(parameterList.get("testExist"),"1",1)) {
            testExist=true;
        }
        parameterMap.put("testExist",testExist);
        /**
         * 调用服务
         */
        WarehouseDO warehouseDO= warehouseService.treeWarehouse(warehouseId,parameterMap);
        WarehouseVO warehouseVO = new WarehouseVO(warehouseDO);
        return Result.ok(warehouseVO);

    }


}